<?php
namespace Common\Model;

class MessageModel extends \Think\Model
{
	//自动验证
	protected $_validate = array(
			//新增
			array('user_id', '/^\d+$/', '请传入用户ID', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
			array('title', '/^1\d{10}$/', '请传入消息标题', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
			array('content', '/^\d+$/', '请传入消息内容', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
			array('type', 'require', '请传入消息类型', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
	);
	
	//自动完成
	protected $_auto = array(
			array('create_time', NOW_TIME, self::MODEL_INSERT, 'string'),
			array('update_time', NOW_TIME, self::MODEL_BOTH, 'string'),
			array('status', 2, self::MODEL_INSERT, 'string'),
	);
	
	/**
	 * 添加消息
	 * @param array $data
	 */
	public function addMessage(array $data)
	{
		if(!$this->create($data)) return array('error' => 1, 'info' => $this->getError());
		$id = $this->add();
		if($id) return array('error' => 0, 'info' => '添加成功'); 
		return array('error' => 1, 'info' => '添加失败');
	}
	
	/**
	 * 查询消息
	 * @param array $where
	 * @param array $option
	 * @param string $order
	 */
	public function searchMessage($where = array(), $option = array(), $order = 'create_time desc, status desc')
	{
		$page = 1;
		$size = 5;
		
		if($option['page'] && $option['size']) {
			$page = $option['page'];
			$size = $option['size'];
			$this->page($page, $size);
		}
		
		//查询消息
		$field = 'id,user_id,title,type,create_time,status';
		if($where  && $where['status'] !== 0 && !$where['status']) $where['status'] = array('gt', 0);
		$message = $this->where($where)->page($page, $size)->field($field)->order($order)->select();
		
		if($message) {
			foreach($message as &$m) {
				$m['type_text'] = C('MESSAGE_TYPE')[$m['type']];
			}
		}
		
		return $message;
	}
	
	/**
	 * 查询用户未读消息数量
	 * @param int|string $userId
	 */
	public function unreadMessageCount($userId)
	{
		if(!$userId) return false;
		$count = $this->where(array('user_id' => $userId))->count();
		
		return $count;
		
	}
}